package com.woniuxy.authapp.app.component;


import com.woniuxy.authapp.service.domain.SecurityUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
 * jwt增强
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        SecurityUser securityUser = (SecurityUser) oAuth2Authentication.getPrincipal();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("LoginId",securityUser.getId());
        hashMap.put("client_id",securityUser.getClientId());
        hashMap.put("LoginName",securityUser.getUsername());

        Collection<? extends GrantedAuthority> authorities = securityUser.getAuthorities();
        ArrayList<String> arrayList = new ArrayList();
        for (GrantedAuthority authority : authorities) {
            String roleId = authority.getAuthority().substring(0, 1);
            arrayList.add(roleId);
        }
        System.out.println(arrayList);
        hashMap.put("LoginRole",arrayList);
        DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) oAuth2AccessToken;
        defaultOAuth2AccessToken.setAdditionalInformation(hashMap);
        return defaultOAuth2AccessToken;
    }
}
